package com.icss.train_sys_back.scheduler;

import com.icss.train_sys_back.service.statistics_manage.PassengerStatisticsService;
import com.icss.train_sys_back.service.statistics_manage.TicketStatisticsManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 统计数据预热定时任务
 * 在业务低峰期将统计数据预先缓存到Redis
 */
@Component
@Slf4j
public class StatisticsCacheScheduler {

    @Autowired
    private PassengerStatisticsService passengerStatisticsService;

    @Autowired
    private TicketStatisticsManageService ticketStatisticsManageService;

    /**
     * 每日凌晨2点执行 - 业务低峰期
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void preloadStatisticsData() {
        log.info("开始预热统计数据到Redis...");
        try {
            // 1. 预热票务统计数据
            preloadTicketStatistics();

            // 2. 预热客流统计数据
            preloadPassengerStatistics();

            log.info("统计数据预热完成");
        } catch (Exception e) {
            log.error("统计数据预热失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 预热票务统计数据
     */
    private void preloadTicketStatistics() {
        log.info("开始预热票务统计数据...");

        // 预热不同时间维度的票务统计数据
        String[] dateTypes = {"day", "week", "month", "year"};
        String[] trainTypes = {"G", "D", "K", "T", null}; // 包含null表示所有类型

        for (String dateType : dateTypes) {
            for (String trainType : trainTypes) {
                try {
                    // 调用方法触发缓存（不关心结果，主要是执行缓存逻辑）
                    ticketStatisticsManageService.ticketStatistics(dateType, trainType, null, null, null);
                    log.info("预热票务统计数据 - 日期类型: {}, 车次类型: {}", dateType, trainType);
                } catch (Exception e) {
                    log.error("预热票务统计数据失败 - 日期类型: {}, 车次类型: {}: {}",
                            dateType, trainType, e.getMessage());
                }
            }
        }

        // 预热销售趋势数据
        try {
            ticketStatisticsManageService.salesTrend();
            log.info("预热销售趋势数据完成");
        } catch (Exception e) {
            log.error("预热销售趋势数据失败: {}", e.getMessage());
        }

        // 预热热门车次和站点数据（本年数据）
        try {
            int year = java.time.LocalDate.now().getYear();
            String startDate = year + "-01-01";
            String endDate = year + "-12-31";

            ticketStatisticsManageService.popularTrains(startDate, endDate);
            ticketStatisticsManageService.popularStations(startDate, endDate);
            log.info("预热热门车次和站点数据完成");
        } catch (Exception e) {
            log.error("预热热门车次和站点数据失败: {}", e.getMessage());
        }
    }

    /**
     * 预热客流统计数据
     */
    private void preloadPassengerStatistics() {
        log.info("开始预热客流统计数据...");

        // 预热不同时间维度的客流统计数据
        String[] dateTypes = {"today", "yesterday", "week", "month", "year"};
        Integer[] stationIds = {null}; // null表示所有站点

        for (String dateType : dateTypes) {
            for (Integer stationId : stationIds) {
                try {
                    // 客流汇总数据
                    passengerStatisticsService.PassengerFlowSummary(dateType, stationId, null, null);

                    // 客流趋势数据
                    passengerStatisticsService.passengerTrend(dateType, stationId, null, null);

                    // 车站分布数据
                    passengerStatisticsService.getStationDistribution(dateType, stationId, null, null);

                    // 时段分布数据
                    passengerStatisticsService.getPassengerTimeDistribution(dateType, stationId, null, null);

                    log.info("预热客流统计数据 - 日期类型: {}, 站点ID: {}", dateType, stationId);
                } catch (Exception e) {
                    log.error("预热客流统计数据失败 - 日期类型: {}, 站点ID: {}: {}",
                            dateType, stationId, e.getMessage());
                }
            }
        }
    }

    /**
     * 每小时执行一次 - 刷新今日数据
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void refreshTodayData() {
        log.info("开始刷新今日统计数据...");

        try {
            // 刷新今日票务数据
            ticketStatisticsManageService.ticketStatistics("day", null, null, null, null);

            // 刷新今日客流数据
            passengerStatisticsService.PassengerFlowSummary("today", null, null, null);
            passengerStatisticsService.passengerTrend("today", null, null, null);
            passengerStatisticsService.getStationDistribution("today", null, null, null);
            passengerStatisticsService.getPassengerTimeDistribution("today", null, null, null);

            log.info("今日统计数据刷新完成");
        } catch (Exception e) {
            log.error("刷新今日统计数据失败: {}", e.getMessage());
        }
    }



}
